<template>
  <view class="container">
    <!-- 头部信息 -->
    <view class="card">
      <view class="section-title">任务信息</view>

      <view class="info-item">
        <text class="info-icon">📍</text>
        <view>
          <view>从: {{ taskInfo.departureLocation }}</view>
          <view>到: {{ taskInfo.destination }}</view>
        </view>
      </view>

      <view class="info-item">
        <text class="info-icon">⏰</text>
        <view>
          <view
            >时间: {{ rawfmtTime(taskInfo.startTime) }} -
            {{ rawfmtTime(taskInfo.endTime) }}</view
          >
          <view>乘客: {{ taskInfo.passengers }}人</view>
        </view>
      </view>

      <view class="info-item">
        <text class="info-icon">🚗</text>
        <view>
          <view>车牌号: {{ taskInfo.plateNumber }}</view>
          <view>任务状态: {{ statusText(taskInfo.status) }}</view>
        </view>
      </view>
    </view>

    <!-- 行程数据 -->
    <view class="card">
      <view class="section-title">行程数据</view>

      <view class="input-item">
        <text class="input-label">行驶里程 (公里)</text>
        <input
          class="input-field"
          type="number"
          v-model="formData.actualMileage"
          placeholder="请输入实际行驶里程"
          @input="calculateTotal"
        />
      </view>

      <view class="input-item">
        <text class="input-label">燃油费用 (元)</text>
        <input
          class="input-field"
          type="digit"
          v-model="formData.fuelCost"
          placeholder="请输入燃油费用"
          @input="calculateTotal"
        />
      </view>

      <view class="input-item">
        <text class="input-label">其他费用 (元)</text>
        <input
          class="input-field"
          type="digit"
          v-model="formData.otherCost"
          placeholder="请输入其他费用"
          @input="calculateTotal"
        />
      </view>

      <view class="input-item">
        <text class="input-label">备注信息</text>
        <textarea
          class="input-field textarea"
          v-model="formData.feedback"
          placeholder="请输入行程相关备注信息"
        />
      </view>
    </view>

    <!-- 照片上传 -->
    <view class="card">
      <view class="section-title">照片上传</view>

      <view class="upload-area" @tap="chooseImage">
        <view class="upload-icon">📁</view>
        <view class="upload-text">点击上传照片</view>
        <view class="upload-hint">支持JPG、PNG格式，最多9张</view>
      </view>

      <view class="image-preview" v-if="uploadedImages.length">
        <view
          class="preview-item"
          v-for="(img, index) in uploadedImages"
          :key="index"
        >
          <image :src="img" mode="aspectFill" />
          <view class="remove-btn" @tap="removeImage(index)">×</view>
        </view>
      </view>
    </view>

    <!-- 费用汇总 -->
    <view class="cost-summary">
      <view class="cost-line">
        <text>燃油费用:</text>
        <text>¥{{ fuelCostFixed }}</text>
      </view>
      <view class="cost-line">
        <text>其他费用:</text>
        <text>¥{{ otherCostFixed }}</text>
      </view>
      <view class="cost-line cost-total">
        <text>总计:</text>
        <text>¥{{ totalCost.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="btn-group">
      <view class="btn btn-outline" @tap="goBack">返回</view>
      <view class="btn btn-primary" @tap="submitCompletion">提交完成</view>
    </view>
  </view>
</template>

<script>
import { formatTaskTime } from "@/utils/formatTaskTime.js";
export default {
  data() {
    return {
      taskInfo: {
        id: "",
        departureLocation: "",
        destination: "",
        startTime: "",
        endTime: "",
        passengers: 0,
        plateNumber: "",
        status: "",
        imgList: [],
      },
      formData: {
        actualMileage: "",
        fuelCost: "",
        otherCost: "",
        feedback: "",
      },
      uploadedImages: [],
      baseCost: 0,
      totalCost: 0,
    };
  },
  onLoad(options) {
    if (options && options.id) {
      this.loadTaskData(options.id);
    }
  },
  computed: {
    fuelCostFixed() {
      return (Number(this.formData.fuelCost) || 0).toFixed(2);
    },
    otherCostFixed() {
      return (Number(this.formData.otherCost) || 0).toFixed(2);
    },
  },
  methods: {
    rawfmtTime: formatTaskTime,

    statusText(status) {
      const map = {
        dispatched: "待接取",
        in_progress: "进行中",
        completed: "已完成",
        cancelled: "已取消",
      };
      return map[status] || status;
    },
    async loadTaskData(id) {
      // 示例：真实场景用 uni.request
      console.log("加载任务数据，ID:", id);
      // 这里可以调用接口获取 taskInfo
      const res = await uni.$http.get(`/sys/orders/getById/${id}`);

      this.taskInfo = res.data.data;
    },
    calculateTotal() {
      const f = Number(this.formData.fuelCost) || 0;
      const o = Number(this.formData.otherCost) || 0;
      this.totalCost = this.baseCost + f + o;
    },
    chooseImage() {
      const left = 9 - this.uploadedImages.length;
      if (left <= 0) {
        uni.showToast({ title: "最多上传9张", icon: "none" });
        return;
      }

      uni.chooseImage({
        count: left,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: async (res) => {
          const tempFiles = res.tempFilePaths; // 选中的临时路径数组
          for (let i = 0; i < tempFiles.length; i++) {
            await this.uploadOne(tempFiles[i]);
          }
        },
      });
    },

    // 单张上传
    uploadOne(tempPath) {
      return new Promise((resolve) => {
        uni.showLoading({ title: "上传中...", mask: true });

        uni.uploadFile({
          url: `${uni.$baseUrl}/file/upload`, // 你的接口
          filePath: tempPath,
          name: "file",
          header: {
            Authorization: uni.getStorageSync("authorization"), // 携带 token
          },

          success: (resp) => {
            uni.hideLoading();
            try {
              const data = JSON.parse(resp.data);

              // 后端返回的是文件名，拼成完整地址
              // 假设你静态资源映射到 /avatar/
              const imgUrl = `${uni.$baseUrl}/file/download?name=${data.message}`;
              this.uploadedImages.push(imgUrl);
            } catch (e) {
              console.log(e);
              uni.showToast({ title: "解析错误", icon: "none" });
            }
          },
          fail: () => {
            uni.hideLoading();
            uni.showToast({ title: "网络错误", icon: "none" });
          },
          complete: () => resolve(),
        });
      });
    },
    removeImage(index) {
      this.uploadedImages.splice(index, 1);
    },
    goBack() {
      uni.navigateBack();
    },
    async submitCompletion() {
      // 1. 校验行驶里程
      const mileage = Number(this.formData.actualMileage);
      if (!mileage || isNaN(mileage) || mileage <= 0) {
        uni.showToast({ title: "请输入正确的行驶里程", icon: "none" });
        return;
      }

      // 2. 校验燃油费用
      const fuel = Number(this.formData.fuelCost);
      if (isNaN(fuel) || fuel < 0) {
        uni.showToast({ title: "请输入正确的燃油费用", icon: "none" });
        return;
      }

      // 3. 校验其他费用
      const other = Number(this.formData.otherCost);
      if (isNaN(other) || other < 0) {
        uni.showToast({ title: "请输入正确的其他费用", icon: "none" });
        return;
      }

      // 4. 全部合法，继续提交
      uni.showLoading({ title: "提交中..." });

      try {
        const payload = {
          id: this.taskInfo.id,
          actualMileage: mileage,
          fuelCost: fuel,
          otherCost: other,
          feedback: this.formData.feedback,
          imgList: this.uploadedImages,
        };

        await uni.$http.put("/sys/orders/completeTask", payload);
        uni.showToast({ title: "提交成功", icon: "success" });

        // 成功后返回上一页或做其它操作
        // setTimeout(() => uni.navigateBack(), 800);
        // 跳转到0级
        uni.switchTab({ url: "/pages/task/task" });
      } catch (err) {
        uni.showToast({ title: "提交失败，请重试", icon: "none" });
      } finally {
        uni.hideLoading();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  background-color: #f5f9ff;
  padding: 20rpx;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica,
    sans-serif;
}

.card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(52, 152, 219, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #2b6cb0;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;

  &::before {
    content: "";
    display: inline-block;
    width: 8rpx;
    height: 32rpx;
    background-color: #3498db;
    margin-right: 16rpx;
    border-radius: 4rpx;
  }
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
  align-items: center;
}

.info-icon {
  margin-right: 20rpx;
  font-size: 36rpx;
}

.input-item {
  margin-bottom: 30rpx;
}

.input-label {
  display: block;
  margin-bottom: 16rpx;
  font-weight: 500;
  color: #2c5282;
  font-size: 28rpx;
}

.input-field {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #bee3f8;
  border-radius: 16rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;

  &.textarea {
    height: 160rpx;
    padding: 20rpx;
  }
}

.upload-area {
  border: 2rpx dashed #90cdf4;
  border-radius: 16rpx;
  padding: 40rpx;
  text-align: center;
  margin-bottom: 30rpx;
  background: #f0f7ff;
}

.upload-icon {
  font-size: 64rpx;
  color: #3498db;
  margin-bottom: 20rpx;
}

.upload-text {
  color: #2b6cb0;
  font-weight: 500;
  font-size: 28rpx;
}

.upload-hint {
  color: #718096;
  font-size: 24rpx;
  margin-top: 16rpx;
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 30rpx;
}

.preview-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

  image {
    width: 100%;
    height: 100%;
  }
}

.remove-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  background: rgba(255, 255, 255, 0.8);
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #e53e3e;
  font-weight: bold;
  font-size: 24rpx;
}

.cost-summary {
  background: #e6f2ff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-top: 30rpx;
}

.cost-line {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #bee3f8;
  font-size: 28rpx;

  &.cost-total {
    font-weight: 700;
    font-size: 32rpx;
    color: #2b6cb0;
    border-bottom: none;
  }
}

.btn-group {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
}

.btn {
  flex: 1;
  height: 90rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-primary {
  background: linear-gradient(135deg, #3498db, #2b6cb0);
  color: white;
  box-shadow: 0 8rpx 20rpx rgba(52, 152, 219, 0.3);
}

.btn-outline {
  background: transparent;
  border: 2rpx solid #3498db;
  color: #3498db;
}
</style>
